package indi.simple.pms.util;

import indi.simple.pms.constant.CommonConstant;
import indi.simple.pms.entity.businessobject.JwtUserBO;
import indi.simple.pms.exception.BadRequestException;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: wanglunhui
 * @Date: 2021/4/13 22:39
 * @Description:
 */
@Component("su")
public class SecurityUtil {

    public static JwtUserBO getJwtUserBO() {
        try {
            JwtUserBO jwtUserBO = (JwtUserBO) getAuthentication().getPrincipal();
            return jwtUserBO;
        } catch (Exception e) {
            throw new BadRequestException(HttpStatus.UNAUTHORIZED, "登录状态过期");
        }
    }

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    public boolean hasAuthority(String authority){
        return hasAnyAuthority(authority);
    }

    public boolean hasAnyAuthority(String... authorities) {
        JwtUserBO jwtUserBO = SecurityUtil.getJwtUserBO();
        if(jwtUserBO.getName().equals(CommonConstant.ADMIN_NAME)){ // 管理员放通
            return true;
        }

        Set<String> allAuthority=jwtUserBO.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toSet());

        for (String authority:authorities){
            if(allAuthority.contains(authority)){
                return true;
            }
        }

        return false;
    }

}

